//
//  SEInquiryViewController.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/4/20.
//

import UIKit
import SnapKit

private let kDiagnosisHeaderDefaultHeight: CGFloat = 200 + UIScreen.navigationBarMaxY

class SEInquiryViewController: SEBaseViewController {
    
    private var viewModel = SEInquiryViewModel()
    
    private let inquiryType: SEInquiryType = .current
    
    override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
    
    private var pullToRefresh: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        viewModel.decodeInquiryModels(type: inquiryType)
        
        beginRefreshing()
        
        viewModel.updateData = { [weak self, viewModel] status in
            self?.tableView.se_empty?.allowShow = true
            switch status {
            case .success:
                self?.tabBarItem.badgeValue = viewModel.messageCount
                self?.tableView.reloadData()
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.beginRefreshing))
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
            self?.endRefreshing()
        }

        viewModel.loadDataHandler = { [weak self] status in
            switch status {
            case .success:
                self?.headerView.updateData(self?.viewModel ?? SEInquiryViewModel())
                self?.sectionHeader.updateData(self?.viewModel ?? SEInquiryViewModel())
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestHomeData), handle: {
                    SEHUD.showError(message: msg)
                })
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }

        }
        
        sectionHeader.rejectedPrescription = { [weak self] in
            self?.pushToPrescriptionRejectedVC()
        }
        sectionHeader.historyDiagnosis = { [weak self] in
            self?.pushToHistoryDiagnosisVC()
        }
        
        SEIMManager.shared.pushMessageHandler = { model in
            switch model.cmd {
            case SEChatCMD.message.rawValue,
                 SEChatCMD.inquiryStatusChanged.rawValue,
                 SEChatCMD.guideInquiryEnd.rawValue:
                self.loadData()
            default:
                break
            }
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestHomeData()
        
        if !pullToRefresh { loadData() }
    }

    override func setupUI() {
        super.setupUI()
        edgesForExtendedLayout = .top
        
        view.addSubview(mainScrollView)
        mainScrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let contentView = UIView()
        contentView.backgroundColor = .background
        mainScrollView.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalToSuperview()
        }
        
        contentView.addSubview(headerView)
        headerView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(kDiagnosisHeaderDefaultHeight)
        }
        
        contentView.addSubview(sectionHeader)
        sectionHeader.snp.makeConstraints { [weak self] (make) in
            guard let self = self else { return }
            make.left.right.equalToSuperview()
            make.top.equalTo(self.headerView.snp.bottom)
            make.height.equalTo(50)
        }
        
        contentView.addSubview(tableView)
        tableView.snp.makeConstraints { [weak self] (make) in
            guard let self = self else { return }
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.sectionHeader.snp.bottom)
        }
    }
    
    override func setupNavBar() {
        super.setupNavBar()
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func didBecomeActive() {
        if !pullToRefresh && inCurrentVC { loadData() }
    }
    
    // MARK: - getter
    
    private lazy var mainScrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.delegate = self
        return scrollView
    }()
    
    private lazy var headerView = UINib.loadViewFrom(SEInquiryHeaderView.self)
    
    private lazy var sectionHeader = UINib.loadViewFrom(SEInquirySectionHeader.self)
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = .background
        tableView.tableFooterView = UIView()
        tableView.estimatedRowHeight = 84
        tableView.rowHeight = UITableView.automaticDimension
        tableView.separatorStyle = .none
        
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.se_header = SERefreshHeader { [weak self] in self?.loadData() }
        tableView.se_footer = SERefreshFooter { [weak self] in self?.loadData(more: true) }
        tableView.se_empty = SEEmptyView { [weak self] in self?.beginRefreshing() }
        
        tableView.register(SEInquiryCell.nibForCell(),
                           forCellReuseIdentifier: SEInquiryCell.reuseIdentifier())
        
        return tableView
    }()
}

extension SEInquiryViewController {

    @objc private func beginRefreshing() {
        pullToRefresh = true
        tableView.se_header?.beginRefreshing()
    }

    private func loadData(more: Bool = false) {
        viewModel.getListOfInquiry(type: inquiryType, more: more)
    }
    
    private func endRefreshing() {
        pullToRefresh = false
        tableView.se_header?.endRefreshing()
        if viewModel.hasMore == false {
            tableView.se_footer?.endRefreshingWithNoMoreData()
        } else {
            tableView.se_footer?.endRefreshing()
        }
    }

    @objc private func requestHomeData() {
        viewModel.requestHomeData()
    }
}

// MARK: - UITableViewDataSource

extension SEInquiryViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEInquiryCell.reuseIdentifier()) as! SEInquiryCell
        cell.update(with: viewModel.viewModel(at: indexPath))
        return cell
    }
}

// MARK: - UITableViewDelegate

extension SEInquiryViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vm = viewModel.viewModel(at: indexPath)
        pushToChatVC(with: vm)
    }
}

// MARK: - push action event
private extension SEInquiryViewController {
    func pushToChatVC(with vm: SEInquiryViewModel) {
        let chatVc = SEChatViewController(infoViewModel: vm, inquiryType: inquiryType)
        chatVc.title = vm.inquiryDetail.patientName
        navigationController?.pushViewController(chatVc, animated: true)
        chatVc.updateInquiryStatusHandler = { self.loadData(more: false) }
    }
    
    func pushToHistoryDiagnosisVC() {
        let historyVc = SEInquiryHistoryViewController()
        historyVc.title = "历史接诊"
        navigationController?.pushViewController(historyVc, animated: true)
    }
    
    func pushToPrescriptionRejectedVC() {
        let rejectedVc = SEPrescriptionRejectedViewController()
        rejectedVc.title = "被驳回的处方"
        navigationController?.pushViewController(rejectedVc, animated: true)
    }
}
